package com.cutefool.zero.code.sso;

import com.cutefool.core.kits.http.Http;
import com.cutefool.core.kits.util.Maps;
import com.cutefool.core.res.Response;
import com.cutefool.zero.code.sso.config.Oauth2Configuration;
import com.cutefool.zero.code.sso.consts.SsoConsts;
import com.cutefool.zero.code.sso.objects.Token;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import okhttp3.Credentials;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class TokenController {

    @Resource
    private Oauth2Configuration oauth2Configuration;

    @PostMapping("/doToken")
    public Response<Token> doLogin(@RequestBody @Validated Param param) {
        Map<String, String> params = Maps.hashMap();
        params.put("code", param.getCode());
        params.put("redirect_uri", param.getCallback());
        params.put("grant_type", "authorization_code");
        params.put("client_id", oauth2Configuration.getClientId());
        params.put("client_secret", oauth2Configuration.getSecret());
        String format = String.format(SsoConsts.GET_TOKEN_URI, oauth2Configuration.getDomain());
        Map<String, String> kvMap = Maps.hashMap();
        Token token = Http.newInstance((s, d) -> s.authenticator((route, response) -> {
                    String basic = Credentials.basic(oauth2Configuration.getClientId(), oauth2Configuration.getSecret());
                    return response.request().newBuilder().header("Authorization", basic).build();
                }))
                .form(format, params, kvMap, new TypeReference<Token>() {
                });
        return Response.ok(token);
    }

    @Data
    public static class Param {

        @NotBlank(message = "回调地址不能为空")
        private String callback;

        @NotBlank(message = "code不能为空")
        private String code;

    }
}
